#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 22:00:15 2025

@author: jack
"""

#%%
from random import randint



# 骰子对象
class Die:

    def __init__(self, num_sides=6):
        self.num_sides = num_sides

    def roll(self):
        return randint(1, self.num_sides)
    
#%%

# 骰子每次的值

die_1 = Die()

throw_times = 1000

results = []

for roll_num in range(throw_times):
    result = die_1.roll()
    results.append(result)

results

#%%

# 6个面出现的频率

freqs = []

for value in range(1, die_1.num_sides+1):

    # 统计results,1-6出现的次数
    freq = results.count(value)
    freqs.append(freq)

freqs
#%%绘制交互图


# 交互图用marimo正常,spyder报错


from plotly.graph_objs import Bar, Layout
from plotly import offline


# plotly不能接受range,需转为list
x_values = list(range(1, die_1.num_sides+1))

# 使用Bar类,data可能包含多个元素,此处必须是list
data = [Bar(x=x_values, y=freqs)]

x_axis_config = {'title': '结果'}
y_axis_config = {'title': '结果的频率'}

# 使用Layout类
my_layout = Layout(title=f'掷一个D6 {throw_times}次的结果', xaxis=x_axis_config, yaxis=y_axis_config)
offline.plot({'data': data, 'layout': my_layout}, filename='d6.html')

#%%

# 2个骰子的概率

_die_1 = Die()
_die_2 = Die()


_throw_times = 1000

_results = []

for _roll_num in range(_throw_times):

    # 计算2个骰子的点数
    _result = _die_1.roll() + _die_2.roll()
    _results.append(_result)




_freqs = []

_max_result = _die_1.num_sides + _die_2.num_sides
for _value in range(2, _max_result+1):

    # 统计results,1-6出现的次数
    _freq = _results.count(_value)
    _freqs.append(_freq)


# plotly不能接受range,需转为list
_x_values = list(range(1,  _max_result+1))

# 使用Bar类,data可能包含多个元素,此处必须是list
_data = [Bar(x=_x_values, y=_freqs)]

# 'dtick': 1,指定x轴间距是1
_x_axis_config = {'title': '结果', 'dtick': 1}
_y_axis_config = {'title': '结果的频率'}

# 使用Layout类
_my_layout = Layout(title=f'掷两个D6 {_throw_times}次的结果', xaxis=_x_axis_config, yaxis=_y_axis_config)
offline.plot({'data': _data, 'layout': _my_layout}, filename='d6_d6.html')